import { BUNDLE_TYPE_ENUM } from "../../base/EnumIndex";
import { TOUCH_MOVE_LEN } from "../../base/GameIndex";
import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import { ResManager1 } from "../../manager/ResManager1";
import LvItem from "../../LvItem";
import LevelPre_18 from "./LevelPre_18";

const { ccclass, property } = cc._decorator;

@ccclass
export default class LvItem_18 extends cc.Component {
    /** 是否可点击  Bool */
    isClick: boolean = true;
    /** 配置信息 */
    config: any = null;
    /** 关卡总类 */
    levelBase: LevelPre_18 = null;

    initSibIndex: number = 0;    //初始化时候得层级
    moenyNum: number = 0;
    /** 绑定的下方Item */
    downItem: cc.Node = null;
    /** 是否已经选中 */
    isKey: boolean = false;
    initItem(config: any, levelBase: LevelPre_18) {
        this.config = config;
        this.levelBase = levelBase;
        this.initSibIndex = this.node.getSiblingIndex();

        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartBack, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchMoveEndBack, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchMoveEndBack, this);
    }
    touchStartPos: cc.Vec3 = null;
    isTouchMove: boolean = false;
    /** 触摸开始回调 */
    touchStartBack(touches: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        this.touchStartPos = cc.v3(touches.getLocation());
        this.isTouchMove = false;
        // this.node.zIndex = 1;
    };
    /** 触摸移动回调 */
    touchMoveBack(touches: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touches.getLocation()) <= TOUCH_MOVE_LEN) { return; }
        this.isTouchMove = true;
    };
    /** 触摸移动结束回调 */
    touchMoveEndBack(touches: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        // this.node.zIndex = 0;
        // this.node.setSiblingIndex(this.initSibIndex);

        if (!this.isTouchMove && this.config.interType == "click") {
            this.runInterEvent();
        }
    };
    clickItem() {
        this.runInterEvent();
    }
    /** 执行此交互事件 */
    runInterEvent() {
        cc.log("runInterEvent", this.isClick, this.isKey)
        if (!this.isClick || this.isKey) { return; }
        this.isKey = true;
        this.isClick = false;

        if (this.config.sayInfo) {
            this.sayNodeTween(this.config.sayInfo);
        } else {
            setTimeout(() => {
                this.levelBase.updateIsWin();
            }, 100);
        }
        if (this.config.addMoney) {
            this.levelBase.updateMoney(this.config.addMoney);
        }
        if (this.config.interTween) {
            this.levelBase.runNodeTween(this.levelBase.viewBg, this.levelBase.getInterTwForName(this.config.interTween).interTween);
        }
        if (!this.config.NorunItems) { // 有这个变量不跑到道具栏
            this.runReturnContent();
            this.levelBase.keyCorret(this);
        }

        // this.levelBase.finishItemArr.push(this);
        // cc.log("finishItemArr.push")
        // if (this.levelBase.finishItemArr.length >= this.levelBase.interJson.keyNum) {
        // }
        // if (this.levelBase.finishItemArr.length == this.levelBase.interJson.keyNum - 1) {
        //     if (this.levelBase.getInterTwForName("overItemTw")) {
        //         this.levelBase.runNodeTween(this.levelBase.viewBg, this.levelBase.getInterTwForName("overItemTw").interTween);
        //     }
        // }
        // let interTw = this.levelBase.getInterTwForName( "finishItem_" + this.levelBase.finishItemArr.length );
        // if( interTw ){
        //     this.levelBase.runNodeTween(this.node, interTw.interTween );
        // }

        // if( this.levelBase.interJson.finishInfos ){   //是否完成特殊item
        //     for (let i = 0; i < this.levelBase.interJson.finishInfos.length; i++) {
        //         const info = this.levelBase.interJson.finishInfos[i];
        //         if( info.nodes.indexOf(this.config.node) < 0 ){
        //             continue;
        //         }
        //         let isRun = true;
        //         for (let j = 0; j < info.nodes.length; j++) {
        //             if( !this.levelBase.isFinishItem(info.nodes[j]) ){
        //                 isRun = false;
        //                 break;
        //             }
        //         }
        //         if( isRun ){
        //             this.levelBase.runNodeTween(this.levelBase.viewBg, this.levelBase.getInterTwForName(info.interTween).interTween);
        //         }
        //     }
        // }

        // if (this.singleRow && this.finishItemArr.length > 3) {
        //     let toX = this.finishItemArr.length < (this.interJson.keyNum - 3) ? -345 + (this.finishItemArr.length - 3) * -100 : this.downContent.parent.width / 2 - this.downContent.width;
        //     cc.tween(this.downContent).to(0.1, { x: toX }).start();
        // }


        this.node.off(cc.Node.EventType.TOUCH_START, this.touchStartBack, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.touchMoveEndBack, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.touchMoveEndBack, this);
        this.node.getComponent(LvItem).isClick = false;
        AudioManager1.playAudio("xuandui", 1, BUNDLE_TYPE_ENUM.GAME);
    };
    /** 执行说话事件 */
    async sayNodeTween(sayInfo: any) {
        let sayNode = this.levelBase.getChildForName(sayInfo.node);
        if (sayInfo.str && AudioManager1.isSubtitle) {
            sayNode.active = true;
            sayNode.getComponent(LvItem).setLabString(sayInfo.str);
        }

        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayNode);
        }
        if (sayInfo.armAni2) {
            this.runArmAni(sayInfo.armAni2, sayInfo.armAni2.shuo, sayNode);
        }

        if (sayInfo.audio) {
            AudioManager1.stopAllAudio();
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);

            cc.Tween.stopAllByTarget(sayNode);
            let tempT = cc.audioEngine.getDuration(audio);
            cc.tween(sayNode)
                .delay(tempT)
                .call(() => {
                    sayNode.active = false;
                    if (sayInfo.armAni) {
                        this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayNode);
                    }
                    if (sayInfo.armAni2) {
                        this.runArmAni(sayInfo.armAni2, sayInfo.armAni.daiji, sayNode);
                    }
                    this.levelBase.updateIsWin();
                }).start();
        } else {
            setTimeout(() => {
                this.levelBase.updateIsWin();
            }, 100);
        }
    };
    /** 通过sayInfo执行龙骨动画 */
    runArmAni(armAni: any, aniName: string, sayNode?: cc.Node) {
        if (!armAni) { return; }
        let node = sayNode.parent;
        if (armAni.node) {
            node = this.levelBase.getNodeForName(armAni.node);
        }
        node.getComponent(LvItem).playArmtureAni(aniName);
    };
    /** 执行本节点返回道具栏 */
    async runReturnContent() {
        let downItem = cc.instantiate(this.levelBase.downItem);
        downItem.getChildByName("itemLab").getComponent(cc.Label).string = this.config.name;
        // downItem.getChildByName("glodLab").getComponent(cc.Label).string = Math.abs(this.config.addMoney).toString();
        downItem.getChildByName("glodLab").getComponent(cc.Label).string = this.config.addMoney.toString();
        downItem.parent = this.levelBase.downContent.children[this.levelBase.finishItemArr.length];
        downItem.position = cc.v3(0, 0, 0);

        if (this.levelBase.interJson["showItemSpr"]) {
            this.downItem = downItem;
            this.moenyNum = this.config.addMoney;
            if (this.config.sprUrl) {
                let itemSpr = await ResManager1.ins.loadRes("spr/" + this.config.sprUrl, cc.SpriteFrame, BUNDLE_TYPE_ENUM.LEVEL);
                Tools.setSpriteFrame(downItem.getChildByName("itemSpr"), itemSpr);
            }
            downItem.getChildByName("itemSpr").getComponent(cc.Sprite).sizeMode = cc.Sprite.SizeMode.TRIMMED;
            this.showYuanNode(true);
            downItem.getChildByName("itemLab").active = true;
            downItem.getChildByName("glodLab").active = true;
            return;
        }

        Tools.setNodeParent(this.node, this.levelBase.viewBg);
        this.node.scale = this.node.scale * this.levelBase.huaNode.scale;
        let toPos = Tools.getToNodePosForNode(downItem, this.levelBase.viewBg);
        // let toPos = cc.v3(0,0,0);
        let tempWidth = Math.max(this.node.width, this.node.height);
        let toScale = downItem.getChildByName("itemSpr").width / tempWidth;
        cc.tween(this.node)
            .to(0.3, { scale: this.node.scale + 0.2, position: cc.v3(0, 0) }).delay(0.5)
            .call(() => {
                cc.tween(this.node)
                    .to(0.15, { position: cc.v3(toPos), scale: toScale })
                    .call(() => {
                        Tools.setNodeParent(this.node, downItem);
                        this.node.position = cc.v3(0, 0, 0)
                        this.node.setSiblingIndex(0);
                        downItem.getChildByName("itemLab").active = true;
                        downItem.getChildByName("glodLab").active = true;
                    }).start();
            }).start();

        this.downItem = downItem;
        this.moenyNum = this.config.addMoney;
    };
    /** 刷新本节点的钱 */
    updateMoeny(moneyNum: number) {
        this.moenyNum += moneyNum;
        this.downItem.getChildByName("glodLab").getComponent(cc.Label).string = this.moenyNum.toString();
    };
    lvYuan: cc.Node = null;
    hongYuan: cc.Node = null;
    /** 显示圆圈 */
    async showYuanNode(isClick: boolean = false) {
        if (!this.node.active) { return; }
        if (this.hongYuan) { return; }
        // cc.log(isClick);
        let yuanNode = null;
        if (isClick == false) {
            let prefab = await ResManager1.ins.loadRes("prefab/node/yuan_Green", cc.Prefab, BUNDLE_TYPE_ENUM.GAME);
            yuanNode = Tools.newPrefab(prefab);
            this.lvYuan = yuanNode;
        } else {
            if (this.lvYuan) {
                this.lvYuan.destroy();
                this.lvYuan = null;
            }
            let prefab = await ResManager1.ins.loadRes("prefab/node/yuan_Red", cc.Prefab, BUNDLE_TYPE_ENUM.GAME);
            yuanNode = Tools.newPrefab(prefab);
            this.hongYuan = yuanNode;
        }

        this.node.parent.addChild(yuanNode);
        if (this.config.yuanScale) {
            yuanNode.setScale(this.config.yuanScale.x, this.config.yuanScale.y);
        } else {
            yuanNode.width = this.node.width;
            yuanNode.height = this.node.height;
        }
        yuanNode.position = this.node.position;
    };
    protected onEnable(): void {
        if (!this.levelBase) {
            return;
        }
        if (!this.levelBase.interJson["showItemSpr"]) {
            return;
        }
        // if (this.node.active == true && !this.lvYuan && !this.hongYuan) {
        //     this.showYuanNode();
        // }
    }

    // onLoad () {}
    // start() {
    // }
    // update (dt) {}
}
